package cn.larry.config;

import java.beans.PropertyEditor;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import cn.larry.config.register.MyPropertyEditorRegistrar_1;
import cn.larry.demo.domain.Person;
import cn.larry.demo.domain.Zoo;
import cn.larry.demo.propertyeditor.ZooEditor;

/**
 * 
 * @author LarryZeal
 *
 */
@Profile("propertyEditor")
@Configuration
public class PropertyEditorConfig {
	// 变态啊，直接调用构造方法
	@Value("${example.person}")
	private Person person;

	@PostConstruct
	public void run() {
		System.out.println("from cn.larry.config.PropertyEditorConfig : " + person);
		// System.out.println(zoo);
	}

	@Bean
	public Person person() {
		return person;
	}

	// 第一种：使用 ConfigurableBeanFactory 接口的 registerCustomEditor() 方法。不推荐
	@Autowired
	private BeanFactory beanFactory;

	@Profile("registerCustomEditor_1")
	@PostConstruct
	public void registerEditors() {
		ConfigurableBeanFactory f = (ConfigurableBeanFactory) beanFactory;
		f.registerCustomEditor(Zoo.class, ZooEditor.class);
	}

	// 第二种：使用CustomEditorConfigurer，这是个bean factory post-processor。
	// 实际上，是通过容器调用post-processor相应的方法实现的自动注册，底层还是第一种方法。
	@Profile("registerCustomEditor_2")
	@Bean
	public CustomEditorConfigurer customEditorConfigurer() {
		CustomEditorConfigurer configurer = new CustomEditorConfigurer();
		Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>();
		customEditors.put(Zoo.class, ZooEditor.class);
		configurer.setCustomEditors(customEditors);
		// configurer.postProcessBeanFactory((ConfigurableListableBeanFactory) beanFactory); // 容器自动调用
		return configurer;
	}
	
	// 第三种
//	@Profile("registerCustomEditor_3")
	@Bean 
	public PropertyEditorRegistrar customPropertyEditorRegistrar(){
		return new MyPropertyEditorRegistrar_1();
	}
	
	@Profile("registerCustomEditor_3")
	@Bean
	public CustomEditorConfigurer customEditorConfigurer1() { // 方法名必须是：customEditorConfigurer。
		CustomEditorConfigurer configurer = new CustomEditorConfigurer();
		configurer.setPropertyEditorRegistrars(new PropertyEditorRegistrar[]{customPropertyEditorRegistrar()});
		return configurer;
	}
}
